<?php
namespace Admin\Api\Controllers;

use Helpers\Main;
use Helpers\Tool;
use Helpers\XhException;
use Admin\Models\sys\XhsysClassification;
use Phalcon\Paginator\Adapter\QueryBuilder;

class FaqController extends ControllerBase
{

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181011
     *
     * @SWG\Get(
     *     path="/api/faq",
     *     tags={"Faq"},
     *     summary="获取列表(分页)",
     *     description="根据分类或编号获取faq常见问题及使用说明",
     *     @SWG\Parameter(name="tag", in="query", description="应用编号(有分类id可不填)", required=false, type="string"),
     *     @SWG\Parameter(name="classifyId", in="query", description="分类id", required=false, type="integer"),
     *     @SWG\Parameter(name="public", in="query", description="是否公开", required=false, type="boolean", default=true),
     *     @SWG\Parameter(name="userType", in="query", required=false, type="integer",
     *          description="用户类型。1=学生,2=教师,3=家长,4=通用",
     *     ),
     *     @SWG\Parameter(name="target", in="query", required=false, type="integer", enum={1,2},
     *          description="目标。1=常见问题,2=使用说明",
     *     ),
     *     @SWG\Parameter(name="keyword", in="query", description="关键词(搜索标题)", required=false, type="string"),
     *     @SWG\Parameter(name="page", in="query", description="页码", type="integer", default="1"),
     *     @SWG\Parameter(name="size", in="query", description="行数", type="integer", default="50"),
     *     @SWG\Response(response=200, description="获取列表成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(
     *                 @SWG\Property(property="id", description="id", type="integer"),
     *                 @SWG\Property(property="title", description="标题", type="string"),
     *                 @SWG\Property(property="answer", description="回答", type="string"),
     *                 @SWG\Property(property="target", description="类型", type="integer"),
     *                 @SWG\Property(property="coverUrl", description="封面地址", type="string"),
     *                 @SWG\Property(property="public", description="是否公开", type="boolean"),
     *                 @SWG\Property(property="userType", description="用户类型", type="integer")
     *             )
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function indexAction()
    {
        $tag        = $this->request->getQuery('tag', 'string');
        $classifyId = $this->request->getQuery('classifyId', 'int');
        $public     = $this->request->getQuery('public', 'string', 'true') == 'true';
        $userType   = $this->request->getQuery('userType', 'int');
        $target     = $this->request->getQuery('target', 'int');
        $keyword    = $this->request->getQuery('keyword', 'string');
        $page       = $this->request->getQuery('page', 'int', 1);
        $size       = $this->request->getQuery('size', 'int', 50);
        if (!$classifyId && !$tag) {
            return $this->sendErrorResponse(400, '分类或标识不可为空');
        }
        try {
            if (!$classifyId && $tag) {
                $classify = XhsysClassification::findFirst([
                    'columns' => 'id',
                    'conditions' => 'bDelete = 0 AND iType = 1 AND sTag = :tag:',
                    'bind'  => ['tag' => $tag]
                ]);
                if (!$classify) {
                    return $this->sendErrorResponse(400, '该应用编号无对应分类');
                }
                $classifyId = $classify->id;
            }

            $builder = $this->modelsManager->createBuilder()
                ->columns([
                    'iFAQId as id',
//                    'iAppCode as tag',
                    'sQuestion as title',
                    'mAnswer as answer',
                    'iTarget as target',
                    'sCoverUrl as coverUrl',
                    'bPublic as public',
                    'iUserType as userType',
                ])
                ->from('Admin\\Models\\faq\\XhfaqInfo')
                ->where(
                    'bDelete = 0 AND bPublic = :public:',
                    ['public' => intval($public)]
                )
                ->andWhere(
                    'iMainClassifyId = :classifyId: OR iClassifyId = :classifyId:',
                    ['classifyId' => $classifyId]
                )
                ->orderBy('iOrderCode DESC');
            if ($target) {
                $builder->andWhere('iTarget = :target:', ['target' => $target]);
            }
            if ($userType) {
                $builder->andWhere('iUserType = :userType:', ['userType' => $userType]);
            }
            if ($keyword) {
//                $builder->andWhere("sQuestion LIKE '%{$keyword}%'");
                $builder->andWhere('sQuestion LIKE :keyword:', ['keyword' => "%{$keyword}%"]);
            }
            $paginate = new QueryBuilder([
                'builder'   => $builder,
                'limit'     => $size,
                'page'      => $page,
            ]);
            $result = $paginate->getPaginate();
            $data   = [
                'page'      => $result->current,
                'size'      => $result->limit,
                'totalPage' => $result->total_pages,
                'total'     => $result->total_items,
                'rows'      => $result->items->toArray()
            ];
            Tool::runInteger($data, ['id', 'userType', 'target']);
            Tool::runEnum($data, ['public' => [0 => false, 1 => true]]);
            return $this->sendJsonResponse($data);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }


    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181011
     *
     * @SWG\Get(
     *     path="/api/faq/classify",
     *     tags={"Faq"},
     *     summary="获取子分类",
     *     @SWG\Parameter(name="tag", in="query", description="应用编号(有分类id可不填)", required=false, type="string"),
     *     @SWG\Parameter(name="classifyId", in="query", description="分类id", required=false, type="integer"),
     *     @SWG\Response(response=200, description="获取列表成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(
     *                 @SWG\Property(property="id", description="id", type="integer"),
     *                 @SWG\Property(property="name", description="分类名", type="string"),
     *                 @SWG\Property(property="tag", description="标识", type="string"),
     *                 @SWG\Property(property="desc", description="描述", type="string"),
     *             )
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function classifyAction()
    {
        $tag        = $this->request->getQuery('tag', 'string');
        $classifyId = $this->request->getQuery('classifyId', 'int');
        if (!$classifyId && !$tag) {
            return $this->sendErrorResponse(400, '分类或标识不可为空');
        }
        try {
            if (!$classifyId && $tag) {
                $classify = XhsysClassification::findFirst([
                    'columns' => 'id',
                    'conditions' => 'bDelete = 0 AND iType = 1 AND sTag = :tag:',
                    'bind'  => ['tag' => $tag]
                ]);
                if (!$classify) {
                    return $this->sendErrorResponse(400, '该应用编号无对应分类');
                }
                $classifyId = $classify->id;
            }
            $classifyInfo = XhsysClassification::find([
                'columns' => ['id', 'name' => 'sName', 'tag' => 'sTag', 'desc' => 'mDesc'],
                'conditions' => 'bDelete = 0 AND iType = 1 AND iParentId = :classifyId:',
                'bind'  => ['classifyId' => $classifyId]
            ])->toArray();
            return $this->sendJsonResponse($classifyInfo);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181011
     *
     * @SWG\Get(
     *     path="/api/faq/hotSearch",
     *     tags={"Faq"},
     *     summary="获取热搜关键词",
     *     @SWG\Parameter(name="tag", in="query", description="应用编号", required=true, type="string"),
     *     @SWG\Response(response=200, description="获取列表成功",
     *         @SWG\Schema(
     *             type="array", description="热搜词"
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function hotSearchAction()
    {
//        $tag        = $this->request->getQuery('tag', 'string');
        $hotSearch = [
            '书架', '布置', '批改', '订正', '统计', '微课', '成绩总表', '纸上做题', '作业卷', '错题库'
//            '云教辅',
//            '题库',
//            '闪退',
//            '错题库',
//            '书架',
//            '自加题库',
//            '自建组',
//            '统计',
//            '成绩总表',
//            '微课'
        ];
        return $this->sendJsonResponse($hotSearch);
    }
}

